package com.bj58.groupbuy.action.controllers;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.web.bind.ServletRequestUtils;

import com.bj58.groupbuy.action.charts.NullResult;
import com.bj58.groupbuy.action.inter.AllianceDataDeal;
import com.bj58.groupbuy.action.inter.AllianceDataSummary;
import com.bj58.groupbuy.action.inter.AmortizeDataDeal;
import com.bj58.groupbuy.action.interceptors.Check;
import com.bj58.groupbuy.action.model.AllianceBillingAttr;
import com.bj58.groupbuy.action.model.Menu;
import com.bj58.groupbuy.action.service.MenuService;
import com.bj58.groupbuy.action.service.OnlineRevenueService;
import com.bj58.groupbuy.action.util.ExcelUtilNew;
import com.bj58.groupbuy.action.util.TemplateMethodFactory;
import com.bj58.groupbuy.action.util.VelocityTools;
import com.bj58.groupbuy.action.util.ZipUtil;
import com.bj58.groupbuy.service.locator.ServiceLocator;
import com.bj58.groupbuy.util.IOUtils;
import com.bj58.groupbuy.util.PathUtil;
import com.bj58.groupbuy.wf.page.Paginate;
import com.bj58.wf.mvc.ActionResult;
import com.bj58.wf.mvc.BeatContext;
import com.bj58.wf.mvc.BeatContext.Model;
import com.bj58.wf.mvc.MvcController;
import com.bj58.wf.mvc.actionresult.ContentResult;
import com.bj58.wf.mvc.annotation.GET;
import com.bj58.wf.mvc.annotation.POST;
import com.bj58.wf.mvc.annotation.Path;
import com.bj58.wf.mvc.client.RequestFile;

/**在线收入数据统计
 * @author sunny3791
 *
 */
@Path("/ors")
public class OnlineRevenueController extends MvcController{
	private OnlineRevenueService onlineRevenueService = ServiceLocator.get(OnlineRevenueService.class);
	private MenuService menuService= ServiceLocator.get(MenuService.class);
	private AllianceDataDeal   allianceDataDeal = new AllianceDataDeal();
	private AllianceDataSummary  ads = new AllianceDataSummary();
	
	/**计费名管理
	 * @return
	 */
	@SuppressWarnings("finally")
	@Path("alliancemanager/{option}")
	@Check("ors/alliancemanager/manager")
	@POST
	@GET
	public ActionResult AllianceManager(String option){
		HttpServletRequest request = beat.getRequest();
		HttpServletResponse response = beat.getResponse();
		Model model= beat.getModel();
		String returnUrl ="";
		TemplateMethodFactory.setVelocityContext("tools", VelocityTools.class, model);
		try{	
			if("manager".equals(option)){  //管理主页面
				//报表管理页
				String source = ServletRequestUtils.getStringParameter(request, "source","");
				String allianceName = ServletRequestUtils.getStringParameter(request, "allianceName","");
				String billingName = ServletRequestUtils.getStringParameter(request, "billingName","");
				String advertType = ServletRequestUtils.getStringParameter(request, "advertType","");
				String channel = ServletRequestUtils.getStringParameter(request, "channel","");
				String cate1 = ServletRequestUtils.getStringParameter(request, "cate1","");
				String cate2 = ServletRequestUtils.getStringParameter(request, "cate2","");
				int pageIndex = ServletRequestUtils.getIntParameter(request, "pageindex", 1);
				int down = ServletRequestUtils.getIntParameter(request,"down",0);
				
				//查询条件组织 以及分页查询参数组织
				StringBuffer where = new StringBuffer(); //查询条件
				StringBuffer url = new StringBuffer(); //分页查询参数
				if(!"".equals(source)){
					where.append(" and  source = '"+source+"'");
					url.append("&source="+source);
				}
				if(!"".equals(allianceName)){
					where.append(" and  allianceName like '%"+allianceName+"%'");
					url.append("&allianceName="+allianceName);
				}
				
				if(!"".equals(billingName)){
					where.append(" and  billingName like '%"+billingName+"%'");
					url.append("&billingName="+billingName);
				}
				
				if(!"".equals(advertType)){
					where.append(" and  advertType like '%"+advertType+"%'");
					url.append("&advertType="+advertType);
				}
				
				if(!"".equals(channel)){
					where.append(" and  channel like '%"+channel+"%'");
					url.append("&channel="+channel);
				}
				
				if(!"".equals(cate1)){
					where.append(" and  cate1 like '%"+cate1+"%'");
					url.append("&cate1="+cate1);
				}
				
				if(!"".equals(cate2)){
					where.append(" and  cate2 like '%"+cate2+"%'");
					url.append("&cate2="+cate2);
				}
				
				//分页查询
				if(down == 0){
					Paginate<AllianceBillingAttr> pList = onlineRevenueService.getAllianceBillingAttrList(where.toString(), 30, pageIndex);
					model.add("pList",pList);
					model.add("rsList",pList.getItems());	
					model.add("paramurl",url.toString());
				}else if(down == 1){
					pageIndex = -1;
					Paginate<AllianceBillingAttr> pList = onlineRevenueService.getAllianceBillingAttrList(where.toString(), 30, pageIndex);
					String [] titles = {"编号","来源","联盟名","广告类型","计费名","渠道","一级类","二级类","是否与合作方分成","计算公式","广告位置","备注","适用时间（开始）","适用时间（结束）","状态"};
					SXSSFWorkbook wwb = ExcelUtilNew.writeExcelCommon("联盟计费名", response, titles, pList.getItems(), AllianceBillingAttr.class,"");
					ExcelUtilNew.downLoadExcel(request, response,"联盟计费名", wwb);
					return new NullResult();
				}
				model.add("allianceName",allianceName);
				model.add("billingName",billingName);
				model.add("advertType",advertType);
				model.add("channel",channel);
				model.add("cate1",cate1);
				model.add("cate2",cate2);
				model.add("pageIndex",pageIndex);
				model.add("source",source);
				
				returnUrl = "ors/orsmanager";
			}else	if("changestate".equals(option)){ //报表状态修改
				String result = "error";
				try{
					int id = ServletRequestUtils.getIntParameter(request, "id", 0);
					int upstate = ServletRequestUtils.getIntParameter(request, "upstate", -1);
					if(id > 0 && upstate > -1){
						AllianceBillingAttr vo = onlineRevenueService.findAllianceBillingAttrById(id);
						if(null != vo ){
							vo.setState(upstate);
							int end = onlineRevenueService.updateAllianceBillingAttr(vo);
							if(end > 0){
								result = "success";
							}
						}
					}
				}catch (Exception e) {
					e.printStackTrace();
				}finally{
					return new ContentResult(result);
				}
			}else if("toedit".equals(option)){ //报表编辑界面
				int id = ServletRequestUtils.getIntParameter(request, "id", 0);
				if(id > 0 ){
					AllianceBillingAttr vo = onlineRevenueService.findAllianceBillingAttrById(id);
					if(null != vo ){
						model.add("vo",vo);
						returnUrl = "ors/editbill";
					}
				}
			}else if("toaddnewbill".equals(option)){ //新增报表页面
				returnUrl = "ors/addnewbill";
			}else if("addnewbill".equals(option) || "updatebill".equals(option)){ //新增OR修改更新报表
				String result = "error";
				try{
					String[] billingattr = ServletRequestUtils.getStringParameters(request, "billingattr");
					if(billingattr.length > 0){
						AllianceBillingAttr vo = new AllianceBillingAttr();
						vo.setSource(billingattr[0]);
						vo.setAllianceName(billingattr[1]);
						vo.setAdvertType(billingattr[2]);
						vo.setBillingName(billingattr[3].trim());
						vo.setChannel(billingattr[4]);
						vo.setCate1(billingattr[5]);
						vo.setCate2(billingattr[6]);
						vo.setFormula(billingattr[7]);
						vo.setAdvertLocation(billingattr[8]);
						vo.setEffectiveTimeStart(billingattr[9]);
						vo.setEffectiveTimeEnd(billingattr[10]);
						vo.setMark(billingattr[11]);
						int share = ServletRequestUtils.getIntParameter(request, "share", 0);
						vo.setIsDividWithPartner(share);
						vo.setState(1);
						if("addnewbill".equals(option)){
							if(onlineRevenueService.addNewAllianceBillingAttr(vo) > 0){
								result = "success";
							}
						}else{
							int id = ServletRequestUtils.getIntParameter(request, "id", 0);
							if(id > 0){
								vo.setId(id);
								if(onlineRevenueService.updateAllianceBillingAttr(vo) > 0){
									result = "success";
								}
							}
						}
					}
				}catch (Exception e) {
					e.printStackTrace();
				}finally{
					return new ContentResult(result);
				}
			}else if("touploadalliandata".equals(option)){
				//k = source  v = allianceName List
				Map<String,List<String>> rsMap = onlineRevenueService.getAllianceList();
				model.add("rsMap",rsMap);
				returnUrl = "ors/uploadalliandata";
			}else if("uploadalliandata".equals(option)){
				String result = "error";
				try {
					Map<String,List<String>> rsMap = onlineRevenueService.getAllianceList();
					
					//需要处理的压缩包  k = source_allName   v = filePath
					Map<String,List<String>> dealFileNameMap = new HashMap<String, List<String>>();
					
					for(Iterator<String> it = rsMap.keySet().iterator(); it.hasNext();){
						String source = it.next();
						List<String> allNameList = rsMap.get(source);
						
						for (String allName : allNameList) {
							RequestFile file = beat.getClient().getUploads().getFile("files" +source + allName);
							if(file.getSize() > 0 ){
								String path = PathUtil.getWFNamespaceFolder()+"/AllianceData/"+source+"/";
								List<String>  fNameList  = ZipUtil.unZip(file.getInputStream(), path);
								dealFileNameMap.put(source + "_" + allName, fNameList);
							}else{
								continue;
							}
						
						}
					}
					
					
					if(dealFileNameMap.size() > 0){
						result = allianceDataDeal.dealAllDatas(dealFileNameMap);
					}
				}catch (Exception e) {
					e.printStackTrace();
				}finally{
					if("success".equals(result)){
						//跳转至查询页面展示最新数据
						Menu menu = menuService.findById(Menu.class, 129);//联盟数据统计节点
						return ActionResult.redirect(menu.getAction());
					}else{
						return new ContentResult(result);
					}
				}
			}else if("tosendemail".equals(option)){
				returnUrl = "ors/tosendemail";
			}else if("exescripts".equals(option)){
				returnUrl = "ors/exescripts";
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return ActionResult.view(returnUrl);
	}
	
	
	/**手动执行发送邮件报告
	 * @return
	 */
	@Path("sendemail")
	@Check("ors/alliancemanager/manager")
	@POST
	public ActionResult sendEmail() {
		return new ActionResult() {
			@Override
			public void render(BeatContext beat)  {
				HttpServletRequest request = beat.getRequest();
				HttpServletResponse response = beat.getResponse();		
				int type = ServletRequestUtils.getIntParameter(request, "type", 0);
				String searchDate = ServletRequestUtils.getStringParameter(request, "searchDate","");
				try {
					EmailReoprtController  erc = new EmailReoprtController();
					int result = 0;
					if(type > 0 && !"".equals(searchDate)){
						result = erc.ReportSend(type,searchDate);//发送邮件
					}
					JSONObject json = new JSONObject();
					json.accumulate("result", result);
					response.setContentType("text/plain; charset=utf-8");
					PrintWriter pw = response.getWriter();
					pw.write(json.toString());
					response.flushBuffer();
					IOUtils.closeQuietly(pw);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
	}
	
	
	/**手动执行在线收入日汇总脚本
	 * @return
	 */
	@SuppressWarnings("finally")
	@Path("orsdaysummary")
	@Check("ors/alliancemanager/manager")
	@POST
	public ActionResult TotalityData (){
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		
		String result = "error";
		try{
			String startDate = ServletRequestUtils.getStringParameter(request, "startDate_orsday","");
			String endDate = ServletRequestUtils.getStringParameter(request, "endDate_orsday","");
			
			if(!"".equals(startDate) && !"".equals(endDate)){
				//删除已有数据
				onlineRevenueService.deleteDaySummary(startDate, endDate);
				//重新汇总插入新数据
				if(ads.dealData(startDate, endDate,0)){
					result = "success";
				}
			}
			model.add("startDate_orsday",startDate);
			model.add("endDate_orsday",endDate);
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			return new ContentResult(result);
		}
	}	
	
	
	/**手动执行在线收入日汇总 - 按月重新计算入库 覆盖原估算值
	 * @return
	 */
	@SuppressWarnings("finally")
	@Path("orsmonthsummary")
	@Check("ors/alliancemanager/manager")
	@POST
	public ActionResult TotalityByMonthData (){
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		
		String result = "error";
		try{
			String startDate = ServletRequestUtils.getStringParameter(request, "startDate_orsmonth","");
			String endDate = ServletRequestUtils.getStringParameter(request, "endDate_orsmonth","");
			
			if(!"".equals(startDate) && !"".equals(endDate)){
				//删除已有数据
				onlineRevenueService.deleteDaySummary(startDate, endDate);
				//重新汇总插入新数据
				if(ads.dealData(startDate, endDate,1)){
					result = "success";
				}
			}
			model.add("startDate_orsday",startDate);
			model.add("endDate_orsday",endDate);
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			return new ContentResult(result);
		}
	}	
	
	@SuppressWarnings("finally")
	@Path({"amortizedata"})
	@Check("ors/alliancemanager/manager")
	@POST
	public ActionResult AmortizeData(){
		HttpServletRequest request = this.beat.getRequest();
	    BeatContext.Model model = this.beat.getModel();

	    String result = "error";
	    try {
	      String startDate = ServletRequestUtils.getStringParameter(request, "startDate_amor", "");
	      String endDate = ServletRequestUtils.getStringParameter(request, "endDate_amor", "");

	      if ((!"".equals(startDate)) && (!"".equals(endDate))) {
	        AmortizeDataDeal deal = new AmortizeDataDeal();
	        if (deal.getPayBalanceCostDetailList(startDate, endDate)) {
	          result = "success";
	        }
	      }
	      model.add("startDate_amor", startDate);
	      model.add("startDate_amor", endDate);
	    } catch (Exception e) {
	      e.printStackTrace();
	    } finally {
	      return new ContentResult(result);
	    }
	}
}
